# KnowledgeQA 部署脚本
# 适用于 Windows 环境

param(
    [string]$Environment = "Development",
    [string]$Configuration = "Debug",
    [string]$OutputPath = ".\publish",
    [switch]$SkipTests,
    [switch]$SkipDatabase
)

Write-Host "=== KnowledgeQA 部署脚本 ===" -ForegroundColor Green
Write-Host "环境: $Environment" -ForegroundColor Yellow
Write-Host "配置: $Configuration" -ForegroundColor Yellow
Write-Host "输出路径: $OutputPath" -ForegroundColor Yellow

# 检查 .NET Core SDK
Write-Host "检查 .NET Core SDK..." -ForegroundColor Cyan
try {
    $dotnetVersion = dotnet --version
    Write-Host "检测到 .NET Core SDK 版本: $dotnetVersion" -ForegroundColor Green
}
catch {
    Write-Host "错误: 未找到 .NET Core SDK，请先安装 .NET Core 6.0 SDK" -ForegroundColor Red
    exit 1
}

# 清理输出目录
if (Test-Path $OutputPath) {
    Write-Host "清理输出目录..." -ForegroundColor Cyan
    Remove-Item -Path $OutputPath -Recurse -Force
}

# 还原依赖包
Write-Host "还原 NuGet 依赖包..." -ForegroundColor Cyan
dotnet restore
if ($LASTEXITCODE -ne 0) {
    Write-Host "错误: 依赖包还原失败" -ForegroundColor Red
    exit 1
}

# 构建项目
Write-Host "构建项目..." -ForegroundColor Cyan
dotnet build --configuration $Configuration --no-restore
if ($LASTEXITCODE -ne 0) {
    Write-Host "错误: 项目构建失败" -ForegroundColor Red
    exit 1
}

# 运行测试
if (-not $SkipTests) {
    Write-Host "运行单元测试..." -ForegroundColor Cyan
    dotnet test --configuration $Configuration --no-build --verbosity normal
    if ($LASTEXITCODE -ne 0) {
        Write-Host "警告: 测试失败，但继续部署" -ForegroundColor Yellow
    }
}

# 发布项目
Write-Host "发布项目..." -ForegroundColor Cyan
dotnet publish --configuration $Configuration --output $OutputPath --no-build
if ($LASTEXITCODE -ne 0) {
    Write-Host "错误: 项目发布失败" -ForegroundColor Red
    exit 1
}

# 创建部署配置文件
Write-Host "创建部署配置..." -ForegroundColor Cyan
$appSettingsPath = Join-Path $OutputPath "appsettings.$Environment.json"
if (-not (Test-Path $appSettingsPath)) {
    Copy-Item "src\KnowledgeQA.API\appsettings.json" $appSettingsPath
    Write-Host "已创建配置文件: $appSettingsPath" -ForegroundColor Green
}

# 创建启动脚本
$startScript = @"
@echo off
echo 启动 KnowledgeQA 系统...
cd /d "%~dp0"
dotnet KnowledgeQA.API.dll --environment $Environment
pause
"@

$startScriptPath = Join-Path $OutputPath "start.bat"
$startScript | Out-File -FilePath $startScriptPath -Encoding ASCII
Write-Host "已创建启动脚本: $startScriptPath" -ForegroundColor Green

# 创建停止脚本
$stopScript = @"
@echo off
echo 停止 KnowledgeQA 系统...
taskkill /f /im dotnet.exe 2>nul
echo 系统已停止
pause
"@

$stopScriptPath = Join-Path $OutputPath "stop.bat"
$stopScript | Out-File -FilePath $stopScriptPath -Encoding ASCII
Write-Host "已创建停止脚本: $stopScriptPath" -ForegroundColor Green

# 创建数据库迁移脚本
if (-not $SkipDatabase) {
    Write-Host "准备数据库迁移..." -ForegroundColor Cyan
    $migrationScript = @"
@echo off
echo 执行数据库迁移...
cd /d "%~dp0"
dotnet ef database update --project src\KnowledgeQA.API --startup-project src\KnowledgeQA.API
echo 数据库迁移完成
pause
"@

    $migrationScriptPath = Join-Path $OutputPath "migrate.bat"
    $migrationScript | Out-File -FilePath $migrationScriptPath -Encoding ASCII
    Write-Host "已创建数据库迁移脚本: $migrationScriptPath" -ForegroundColor Green
}

# 创建 README 文件
$readmeContent = @"
# KnowledgeQA 部署包

## 快速开始

1. 配置数据库连接字符串（编辑 appsettings.$Environment.json）
2. 配置 OpenAI API 密钥（编辑 appsettings.$Environment.json）
3. 运行数据库迁移：`migrate.bat`
4. 启动系统：`start.bat`
5. 停止系统：`stop.bat`

## 访问地址

- Web 界面：http://localhost:5000
- API 文档：http://localhost:5000/swagger

## 配置说明

### 数据库配置
```json
{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=KnowledgeQA.db"
  }
}
```

### OpenAI 配置
```json
{
  "OpenAI": {
    "ApiKey": "your-api-key-here",
    "Model": "gpt-3.5-turbo"
  }
}
```

## 注意事项

1. 确保已安装 .NET Core 6.0 Runtime
2. 确保有足够的磁盘空间存储文档和向量数据
3. 生产环境建议使用反向代理（如 Nginx）
4. 定期备份数据库文件

## 故障排除

### 常见问题

1. **端口被占用**：修改 appsettings.json 中的端口配置
2. **数据库连接失败**：检查连接字符串和文件权限
3. **API 调用失败**：检查 OpenAI API 密钥配置
4. **文件上传失败**：检查上传目录权限

### 日志查看

日志文件位置：`logs/` 目录
"@

$readmePath = Join-Path $OutputPath "README.md"
$readmeContent | Out-File -FilePath $readmePath -Encoding UTF8
Write-Host "已创建说明文档: $readmePath" -ForegroundColor Green

# 创建日志目录
$logsPath = Join-Path $OutputPath "logs"
New-Item -ItemType Directory -Path $logsPath -Force | Out-Null
Write-Host "已创建日志目录: $logsPath" -ForegroundColor Green

# 创建上传目录
$uploadsPath = Join-Path $OutputPath "uploads"
New-Item -ItemType Directory -Path $uploadsPath -Force | Out-Null
Write-Host "已创建上传目录: $uploadsPath" -ForegroundColor Green

Write-Host "=== 部署完成 ===" -ForegroundColor Green
Write-Host "部署路径: $OutputPath" -ForegroundColor Yellow
Write-Host "下一步：" -ForegroundColor Cyan
Write-Host "1. 配置 appsettings.$Environment.json" -ForegroundColor White
Write-Host "2. 运行 migrate.bat 进行数据库迁移" -ForegroundColor White
Write-Host "3. 运行 start.bat 启动系统" -ForegroundColor White 